import { CartItem } from "../store";
import { handleResponse, Result } from "../util/handler";

async function addItemsToCartAsync(items: CartItem[], token: string): Promise<Result<null>> {
  return await fetch('/api/cart', {
    method: 'post',
    body: new URLSearchParams({ 'str': JSON.stringify(items) }),
    credentials: 'same-origin',
    headers: {
      'content-type': 'application/x-www-form-urlencoded',
      token
    }
  }).then((resp) => handleResponse<null>(resp));
}

async function getItemsFromCartAsync(token: string): Promise<Result<string | null>> {
  return await fetch('/api/cart', {
    method: 'get',
    credentials: 'same-origin',
    headers: {
      token
    }
  }).then((resp) => handleResponse<string | null>(resp));
}

export {
  addItemsToCartAsync,
  getItemsFromCartAsync
}